<?php
/**
 *  消息通知
 * Author:Jasmine
 * Date: 2016/4/26
 * Time: 13:54
 */
namespace Common\Model;

class NoticeModel extends BaseModel{
    //通知类型相关
    const NOTICE_TYPE_PRAISE        =1;//点赞操作
    const NOTICE_TYPE_COMMENT       =2;//评论操作
    const NOTICE_TYPE_SYSTEM_MSG    =3;//系统消息
    const NOTICE_TYPE_LOGISTICS     =4;//物流状态
    const NOTICE_TYPE_TOY           =5;//易物交换

    //通知消息的目标
    const NOTICE_TARGET_ARTICLE     =1;//文章
    const NOTICE_TARGET_EVENT       =2;//活动
    const NOTICE_TARGET_COMMENT     =3;//评论
    const NOTICE_TARGET_STORE       =4;//门店
    const NOTICE_TARGET_POINTMALL   =5;//积分商城
    const NOTICE_TARGET_GOODS       =6;//跨电商商品
    const NOTICE_TARGET_POINTLOTTERY=7;//积分抽奖

    //评论点赞操作
    const NOTICE_OP_RECEIVECOMMENT      =0;//接收到的评论
    const NOTICE_OP_SENDCOMMENT         =1;//发出的评论
    const NOTICE_OP_RECEIVEPRAISE      =2;//接收到的点赞
    const NOTICE_OP_SENDPRAISE         =3;//发出的点赞

    //新消息状态
    const NOTICE_HAVE_NEW           =1;//有新消息
    const NOTICE_NO_NEW             =0;//没有新消息

    //保存通知信息(点赞，评论，站内信……)
    public static function saveNotice($type,$target,$objID,$fromUid,$toUid,$title,$content,$link=''){
        $dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
        $dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
        $praiseInfo=M('u_user_base',null,DB_MAIN_CFG)->where("uid={$fromUid}")->find();
        $data=array();
        $data['type']=$type;                                            //操作类型（点赞、评论）
        $data['target']=$target;                                        //操作目标（文章）
        $data['objID']=$objID;                                          //对象ID
        $data['fromUid']=$fromUid;                                      //动作人ID
        $data['toUid']=$toUid;                                          //被动作人ID
        switch($type){
            case self::NOTICE_TYPE_PRAISE:
                $data['icon']=$fromUid;                                 //图标(存用户ID)
                $data['title']=$praiseInfo['nickname'];                 //动作人昵称（消息标题）
                $data['content']="点赞了你的文章《".$title."》";           //消息内容
                break;
            case self::NOTICE_TYPE_COMMENT:
                $data['icon']=$fromUid;                                 //图标(存用户ID)
                $data['title']=$praiseInfo['nickname'];                 //动作人昵称（消息标题）
                $data['content']="评论了你的文章《".$title."》";           //消息内容
                break;
            case self::NOTICE_TYPE_SYSTEM_MSG:
                $data['icon']=$fromUid;                                 //图标(系统消息统一图标)
                $data['title']=$title;                                  //系统消息标题
                $data['content']=$content;                              //系统消息内容
                $data['link']=$link;                                    //链接地址
                break;
        }
        $data['noticeTime']=time();                                     //消息发布时间
        $uinfo=array(
            'uid'=>fromUid,
            'nickname'=>$data['title']
        );

        if($data['fromUid']!=$data['toUid']){
            $res=M('notice_msg',null,DB_MAIN_CFG)->add($data);
            if($res===false){
                $dataFailure['msg']="发送失败";
                return $dataFailure;
            }
            self::addRedPrompt($toUid,$type);
            $dataSuccess['msg']="发送成功";
            return $dataSuccess;
        }
        else
            return $dataFailure;
    }

    public static function addRedPrompt($toUid,$type){
        //更新红点状态
        switch($type){
            case self::NOTICE_TYPE_PRAISE:
                $field = 'praise';
                break;
            case self::NOTICE_TYPE_COMMENT:
                $field = 'comment';
                break;
            case self::NOTICE_TYPE_SYSTEM_MSG:
                $field = 'system';
                break;
            case self::NOTICE_TYPE_TOY:
                $field='toy';
                break;
            default:
                return false;
        }
        $promptM = M('red_prompt',null,DB_MAIN_CFG);
        if($promptM->where("uid={$toUid}")->find()){
            $promptM->where("uid={$toUid}")->setField($field,self::NOTICE_HAVE_NEW);
        } else {
            $data = array(
                'uid'     => $toUid,
                $field    => self::NOTICE_HAVE_NEW,
            );
            $promptM->add($data);
        }
    }
    public static function resetRedPrompt($toUid,$type){
        //更新红点状态
        switch($type){
            case self::NOTICE_TYPE_PRAISE:
                $field = 'praise';
                break;
            case self::NOTICE_TYPE_COMMENT:
                $field = 'comment';
                break;
            case self::NOTICE_TYPE_SYSTEM_MSG:
                $field = 'system';
                break;
            case self::NOTICE_TYPE_TOY:
                $field='toy';
                break;
            default:
                return false;
        }
        M('red_prompt',null,DB_MAIN_CFG)->where("uid={$toUid}")->setField($field,self::NOTICE_NO_NEW);

    }

    //保存系统公告消息
    public static function saveSystemNotice($title,$content,$link=''){
        $dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
        $dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
        $nowTime = time();
        $data=array(
            'type'      => self::NOTICE_TYPE_SYSTEM_MSG,
            'icon'      => 0,
            'title'     => $title,
            'content'   => $content,
            'link'      => $link,
            'noticeTime'=> $nowTime
        );
        $res = M('notice_system',null,DB_MAIN_CFG)->add($data);
        if($res===false){
            $dataFailure['msg']="发送失败";
            return $dataFailure;
        }

        $dataSuccess['msg']="发送成功";
        return $dataSuccess;
    }

    /**
     * 系统公告发布后，改变红点状态
     * Author: wuwl
     * @param $uid
     * @return int
     */
    public static function changeSystemAllRed($uid){
        $noticeM = M('notice_msg',null,DB_MAIN_CFG);
        $noticeAllM = M('notice_system',null,DB_MAIN_CFG);

        $newSystemNotice = $noticeAllM->order("noticeTIme DESC")->find();
        if(!$newSystemNotice || $noticeM->where("objID={$newSystemNotice['id']} and toUid={$uid} and type=".self::NOTICE_TYPE_SYSTEM_MSG)->find()){
            $systemFlag=0;
        } else {
            $systemFlag=1;
        }

        return $systemFlag;
    }

    //获取我的评论和点赞
    public static function getMyMessage($uid,$type,$page,$pageSize){
        $dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
        $dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

        if(!$uid){
            $dataFailure['msg']="请登录后操作";
            return $dataFailure;
        }

        $noticeM = M('notice_msg',null,DB_MAIN_CFG);
        switch($type){
            case self::NOTICE_OP_RECEIVECOMMENT:
                $where = "toUid={$uid} and type=".self::NOTICE_TYPE_COMMENT;
                break;
            case self::NOTICE_OP_SENDCOMMENT:
                $where = "fromUid={$uid} and type=".self::NOTICE_TYPE_COMMENT;
                break;
            case self::NOTICE_OP_RECEIVEPRAISE:
                $where = "toUid={$uid} and type=".self::NOTICE_TYPE_PRAISE;
                break;
            case self::NOTICE_OP_SENDPRAISE:
                $where = "fromUid={$uid} and type=".self::NOTICE_TYPE_PRAISE;
                break;
        }

        $dataSuccess['total'] =$noticeM ->where($where)->count();                              //获取数据总条数
        $dataSuccess['page'] = $page ? $page :1;                                                //返回当前页数
        $dataSuccess['totalPage'] = ceil($dataSuccess['total']/$pageSize);						//总页数
        $dataSuccess['nextPage'] = $dataSuccess['page'] >=$dataSuccess['totalPage']?0:1;		//是否还有下一页
        $offset = ($dataSuccess['page']-1)*$pageSize;

        $list = $noticeM
                ->where($where)
                ->limit($offset,$pageSize)
                ->order("noticeTime DESC")
                ->select();

        foreach($list as $k => $v){
            if($type==0 || $type==1){
                $info = M('comment_1',null,DB_MAIN_CFG)->where("objID={$list[$k]['objID']} and uid={$list[$k]['fromUid']}")->field('content')->find();
                $list[$k]['comment'] = $info['content'];
            }
            $article = M('article',null,DB_MAIN_CFG)->where("id={$list[$k]['objID']}")->field('nickname,title,listPic')->find();
            $list[$k]['nickname'] = $article['nickname'];
            $list[$k]['objTitle'] = $article['title'];
            $list[$k]['articlePic'] = $article['listPic'];
        }

        //改变红点提示表中对应的状态
        $promptM = M('red_prompt',null,DB_MAIN_CFG);
        switch($type){
            case self::NOTICE_OP_RECEIVECOMMENT:
                $promptM->where("uid={$uid}")->setField('comment',self::NOTICE_NO_NEW);
                break;
            case self::NOTICE_OP_RECEIVEPRAISE:
                $promptM->where("uid={$uid}")->setField('praise',self::NOTICE_NO_NEW);
        }
        $dataSuccess['data']=$list;
        return $dataSuccess;

    }


    /**
     * 获取用户所有消息通知
     * @param $uid
     * @param $page
     * @param $pageSize
     * @param int $type
     * @return array
     */
    public static function myAllMessage($uid,$page,$pageSize,$type=0){
        $dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
        $dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
        if(!$uid){
            $dataFailure['msg']="请登录后操作";
            return $dataFailure;
        }
        $noticeM = M('notice_msg',null,DB_MAIN_CFG);
        $noticeAllM = M('notice_system',null,DB_MAIN_CFG);

        $systemNotice = $noticeAllM->order("noticeTime DESC")->select();
        foreach($systemNotice as $key => $value){
            if(!$noticeM->where("objID={$value['id']} and toUid={$uid} and type=".self::NOTICE_TYPE_SYSTEM_MSG)->find()){
                $data = array(
                    'type'      => self::NOTICE_TYPE_SYSTEM_MSG,
                    'target'    => 0,
                    'objID'     => $value['id'],
                    'fromUid'   => 0,
                    'toUid'     => $uid,
                    'icon'      => 0,
                    'title'     => $value['title'],
                    'content'   => $value['content'],
                    'link'      => $value['link'],
                    'noticeTime'=> $value['noticeTime'],
                    'del'       => 0,
                );
                $noticeM->add($data);
            }
        }
        if($type == self::NOTICE_TYPE_SYSTEM_MSG){
            $where = "toUid={$uid} and del=0 and type=".self::NOTICE_TYPE_SYSTEM_MSG;
        }else{
            $where = "toUid={$uid} and del=0";
        }
        $dataSuccess['total'] = $noticeM->where($where)->count();                               //获取数据总条数
        $dataSuccess['page'] = $page ? $page :1;                                                //返回当前页数
        $dataSuccess['totalPage'] = ceil($dataSuccess['total']/$pageSize);						//总页数
        $dataSuccess['nextPage'] = $dataSuccess['page'] >=$dataSuccess['totalPage']?0:1;		//是否还有下一页
        $offset = ($dataSuccess['page']-1)*$pageSize;

        $dataSuccess['list'] = $noticeM
            ->where($where)
            ->limit($offset,$pageSize)
            ->order("noticeTime DESC")
            ->select();

        //改红点状态
        $promptM = M('red_prompt',null,DB_MAIN_CFG);
        switch($type){
            case self::NOTICE_TYPE_SYSTEM_MSG:
                $promptM->where("uid={$uid}")->setField('system',self::NOTICE_NO_NEW);
                break;
            case 0:
                $data = array(
                    'praise' =>self::NOTICE_NO_NEW,
                    'comment'=>self::NOTICE_NO_NEW,
                    'system' =>self::NOTICE_NO_NEW,

                );
                $promptM->where("uid={$uid}")->save($data);
                break;
        }
        return $dataSuccess;
    }


    /**
     * 查询是否出现红点提示
     * author: wwl <wuwl@soe-soe.com>
     * Return: $flag
     * Address: 浙江宣逸网络科技有限公司
     */
    public static function checkRedPrompt($uid,$type=0){
        $dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
        $dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
        if(!$uid){
            $dataFailure['msg']="请登录后操作";
            return $dataFailure;
        }
        $promptM = M('red_prompt',null,DB_MAIN_CFG);

        switch($type){
            case self::NOTICE_TYPE_TOY:
                $flag = $promptM->where("uid={$uid} and toy=1")->find()? 1:0;
                break;
            case self::NOTICE_TYPE_PRAISE:
                $flag = $promptM->where("uid={$uid} and praise=1")->find()? 1:0;
                break;
            case self::NOTICE_TYPE_COMMENT:
                $flag = $promptM->where("uid={$uid} and comment=1")->find()? 1:0;
                break;
            case self::NOTICE_TYPE_SYSTEM_MSG:
                $flag = $promptM->where("uid={$uid} and system=1")->find()? 1:0;
                if($flag==0){
                    $flag = self::changeSystemAllRed($uid);
                }
                break;
            default:
                $flag = $promptM->where("uid={$uid} and (praise=1 or comment=1 or system=1 or toy=1)")->find()? 1:0;
                if($flag==0){
                    $flag = self::changeSystemAllRed($uid);
                }
                break;
        }
        return $flag;
    }

    //删除消息通知
    public static function del($id,$uid=0){
        $dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
        $dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
        if(!$id) return $dataFailure;
        $noticeM = M('notice_msg',null,DB_MAIN_CFG);
        $type = $noticeM->where("id={$id}")->getField('type');

        if($type==self::NOTICE_TYPE_SYSTEM_MSG){
            $delete = $noticeM->where("id={$id} and toUid={$uid}")->setField('del',1);
        }else{
            $delete = $noticeM->where("id={$id} and toUid={$uid}")->delete();
        }

        if($delete===false){
            $dataFailure['msg']="删除失败";
            return $dataFailure;
        }else{
            $dataSuccess['msg']="成功删除1条数据";
            return $dataSuccess;
        }

    }
    //清空消息通知
    public static function delAll($uid){
        $dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
        $dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
        if(!$uid) return $dataFailure;

        $noticeM = M('notice_msg',null,DB_MAIN_CFG);
        $row = $noticeM->where("toUid={$uid} and del=0")->count();    //统计删除数据

        $type = $noticeM->where("toUid={$uid} and del=0")->field('type,id')->select();

        foreach($type as $val){
            if($val['type']==self::NOTICE_TYPE_SYSTEM_MSG){
                $delete = $noticeM->where("id={$val['id']}")->setField('del',1);
            }else{
                $delete = $noticeM->where("id={$val['id']}")->delete();
            }
            if($delete===false){
                $dataFailure['msg']="删除失败";
                return $dataFailure;
            }
        }
        $dataSuccess['msg']="成功删除".$row."条数据";
        return $dataSuccess;

    }

}